
#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    server = new QTcpServer(this);
    m_flushTimer = new QTimer(this);
    m_flushTimer->setSingleShot(true); // 单次触发
    connect(m_flushTimer, &QTimer::timeout, this, &Widget::sendNextFlushItem);


    nextRequestId =0;
    sqlinit();
    //当服务器队列中一有客户端请求，就立即触发newConnect信号
    connect(server,&QTcpServer::newConnection,this,&Widget::newConnection);
    //设置按键使能
    ui->pushButton_3->setEnabled(false);
}

void delay_ms(uint32_t ms)
{
    uint32_t i, j;
    for (i = 0; i < ms; i++)
        for (j = 0; j < 8000; j++);
}
Widget::~Widget()
{
    delete ui;
}
//快递员注册功能实现
int Widget::courier_register(sendRig *str)
{
//    ui->textEdit->append(str->Account);
//    ui->textEdit->append(str->password);
//    ui->textEdit->append(str->tele);
//    ui->textEdit->append(QString::number(str->IC));
    QSqlQuery query;
    if(str->IC != 224){//邀请码判断
        return 0;
    }
    QString sql = QString("insert or ignore into user values('%1', '%2', %3, '%4', '%5', %6);")
            .arg(str->Account)
            .arg(str->password)
            .arg(0)
            .arg(str->tele)
            .arg(0)
            .arg(str->IC);
    query.prepare(sql);
    if(!query.exec()){
        qDebug() << "insert: " << query.lastError().text();
        return 0;
    }
    if(query.numRowsAffected()<=0){
        ui->textEdit->append("hulue");
        return -1;
    }
    return 1;
}
//用户注册
int Widget::consignee_register(sendRig *str)
{
    QSqlQuery query;
    QString sql = QString("insert or ignore into user values('%1', '%2', %3, '%4', '%5', %6);")
            .arg(str->Account)
            .arg(str->password)
            .arg(1)
            .arg(str->tele)
            .arg(0)
            .arg(0);
    query.prepare(sql);
    if(!query.exec()){
        qDebug()<<"insert:"<<query.lastError().text();
        return 0;
    }
    if(query.numRowsAffected()<=0)
        return -1;
    return 1;
}
//登录系统
int Widget::user_login(sendRig *str,sendRig * str1)
{
    ui->textEdit->append(str->tele);
    ui->textEdit->append(str->password);
    qDebug() << "Raw bytes:" << QByteArray(str->password).toHex();
    QSqlQuery query;
    QString sql = QString("select * from user where tele='%1';")
            .arg(str->tele);

    query.prepare(sql);
    if(!query.exec()){
        qDebug()<<"insert:"<<query.lastError().text();
        return -2;
    }

    int i=6;
    while(i--){
        qDebug()<<i<<":"<<str->password[i];


    }
    if(query.next())
    {
        ui->textEdit->append(query.value("Password").toString().trimmed());
        ui->textEdit->append(QString::number(query.value("Password").toString().trimmed().size()));
        ui->textEdit->append(QString::fromUtf8(str->password));
        ui->textEdit->append(QString::number(QString::fromUtf8(str->password).size()));



        if(query.value("Password").toString().trimmed()==QString::fromUtf8(str->password).trimmed())
//        if(strcmp(query.value("Password").toString().toUtf8(),str->password)==0)
        {
            strcpy(str1->tele,query.value("tele").toString().toUtf8());
            ui->textEdit->append(str1->tele);
            if(0==query.value("type").toString().compare("0"))
            {
                return 1;
            }else{
                return 2;
            }
        }else{
            return 0;
        }
    }else{
        return -1;
    }
}
//订单信息录入
int Widget::stg_read(sendRig *str)
{
    QSqlQuery query;


    QString sql = QString("insert into orders values('%1', '%2', '%3', '%4', '%5', '%6');")
            .arg(str->Account)
            .arg(str->ID)
            .arg(str->tele)
            .arg(str->teletwo)
            .arg("sending")
            .arg("-");
    query.prepare(sql);
    if(!query.exec()){
        qDebug()<<"insert:"<<query.lastError().text();
        return 0;
    }
    return 1;
}
//用户刷新数据功能
int Widget::usr_flush(sendRig *str,int m)
{
    ui->textEdit->append(str->tele);
    QString sql;
    if(str->IC == 0){
    sql = QString("select * from orders where ctele='%1' and state != 'finished';")
            .arg(str->tele);
    }else if(str->IC ==1){
        sql = QString("select * from orders where rtele='%1' and state != 'finished';")
                .arg(str->tele);
    }
    QSqlQuery query;
    query.prepare(sql);
    if(!query.exec()){
        qDebug()<<"insert:"<<query.lastError().text();
        return 0;
    }

//    query.next();
   // qDebug()<<query.value("UID").toString();
    while(query.next()){
        qDebug()<<"--------";
        sendRig mess;
        mess.type=4;
        strcpy(mess.Account,query.value("name").toString().toUtf8());
        strcpy(mess.ID,query.value("UID").toString().toUtf8());
        strcpy(mess.state,query.value("state").toString().toUtf8());
        strcpy(mess.password,query.value("idenma").toString().toUtf8());
        ui->textEdit->append(QString("%1+%2+%3+%4").arg(mess.Account).arg(mess.ID).arg(mess.state).arg(mess.password));
        m_flushQueue.enqueue(qMakePair(mess, m));
//        QByteArray da;
//        da.append((char*)&mess,sizeof (sendRig));
//        tcpClientList.at(m)->write(da);

    }
    if (!m_flushQueue.isEmpty()) {
            sendNextFlushItem();
        }
    return 1;
}

void Widget::sendNextFlushItem()
{
    if (m_flushQueue.isEmpty()) {
            qDebug() << "刷新数据发送完成";
            return;
        }
    QPair<sendRig, int> item = m_flushQueue.dequeue();
        sendRig mess = item.first;
        int clientIndex = item.second;
        QByteArray da(reinterpret_cast<char*>(&mess), sizeof(sendRig));
        tcpClientList.at(clientIndex)->write(da);
        // 如果队列中还有更多数据，设置定时器发送下一条
            if (!m_flushQueue.isEmpty()) {
                // 设置延时时间（毫秒）
                m_flushTimer->start(1000);
            }
}



//空柜信息请求
void Widget::empty_whitch(sendRig *str,int i)
{
//    sendRig mess;

//    nextRequestId++;
//    mess.IC = i;
//    //requestMap[mess.IC]=tcpClientList.at(i);

//    mess.type = 5;
//    QByteArray data;
//    data.append((char*)&mess,sizeof (sendRig));
//    QString wh = QString(str->Account);
//    qDebug()<<str->ID<<"+"<<wh<<"ip:"<<i;
//    tcpClientList.at(wh.toInt()-1)->write(data);

    sendRig mess;

    nextRequestId++;
    mess.IC = i;
    //requestMap[mess.IC]=tcpClientList.at(i);

    mess.type = 5;

    int randomNum = QRandomGenerator::global()->bounded(100, 1000);
    QSqlQuery queryy;
    QString sqll = QString("update orders set idenma='%1' where UID='%2'")
            .arg(QString::number(randomNum))
            .arg(str->ID);
    queryy.prepare(sqll);
    queryy.exec();

    QSqlQuery query_save;
    QString sql_save = QString("select * from orders where UID='%1';").arg(str->ID);
    query_save.prepare(sql_save);
    if(!query_save.exec()){
        qDebug()<<"select:"<<query_save.lastError().text();
    }

    query_save.next();

    strcpy(mess.Account,query_save.value("name").toString().toUtf8());
    strcpy(mess.ID,query_save.value("UID").toString().toUtf8());
    strcpy(mess.tele,query_save.value("ctele").toString().toUtf8());
    strcpy(mess.teletwo,query_save.value("rtele").toString().toUtf8());
    strcpy(mess.password,query_save.value("idenma").toString().toUtf8());




//    strcpy(mess.ID,str->ID);
//    strcpy(mess.Account,str->Account);
    QByteArray data;
    data.append((char*)&mess,sizeof (sendRig));
    QString wh = QString(str->tele);
    qDebug()<<str->ID<<"+"<<wh.toInt()<<"ip:"<<i;
    tcpClientList.at(0)->write(data);
}
//存件反馈
void Widget::in_return(sendRig *str)
{

    QSqlQuery query;
    QString sql = QString("update orders set state='arrive' where UID='%1';")
            .arg(str->ID);
    query.prepare(sql);
    if(!query.exec()){
        qDebug()<<"update:"<<query.lastError().text();
    }
}
//取件反馈
void Widget::out_return(sendRig *str)
{
    QSqlQuery query;
    QString sql = QString("update orders set state='finished' where UID='%1';")
            .arg(str->ID);
    query.prepare(sql);
    if(!query.exec()){
        qDebug()<<"update:"<<query.lastError().text();
    }
}
// 数据库初始化
void Widget::sqlinit()
{
    qDebug()<<"driver:"<<QSqlDatabase::drivers();
    if(QSqlDatabase::contains("qt_sql_default_connection")){
        db = QSqlDatabase::database("qt_sql_default_connection");
    }else{
        db = QSqlDatabase::addDatabase("QSQLITE");
    }

    db.setDatabaseName("fuwo.db");
    if(db.isOpen()){
        return;
    }else{
        if(!db.open()){
            qDebug() << "open: " << db.lastError().text();              // lastError()：获取最新的数据库错误， text()：获取错误的文本信息
            return;
        }
    }
    qDebug() << "数据库打开成功";
    QString sql = "create table if not exists user(Account test, Password char, type int, tele char uique not NULL, id char, IC int);";

    QSqlQuery query;       //定义初始化 sql指令操作的对象
    if(!query.exec(sql)){          //执行sql指令
        qDebug() << "create: " << query.lastError().text();
    }

//    QString sql_roder = "create table if not exists order(name test, UID char, ctele char, rtele char, state char, idenma char);";
//    QSqlQuery query_order;
//    query_order.prepare(sql_roder);
    if(!query.exec("create table if not exists orders(name test,UID char, ctele char, rtele char, state char, idenma char);")){          //执行sql指令
        qDebug() << "create: " << query.lastError().text();
    }
}
void Widget::on_pushButton_clicked()
{
    qDebug()<<"队列："<<server->maxPendingConnections();
    //监听服务器，即启动服务器
    if(!server->listen(QHostAddress::AnyIPv4,ui->lineEdit_2->text().toInt()))
    {
        ui->textEdit->append("连接失败:"+server->errorString());
        ui->label->setStyleSheet("background-color:red;border-radius:50px;");

        return;
    }
    ui->textEdit->append("服务器启动成功");
    ui->label->setStyleSheet("background-color:green;border-radius:50px;");
}


void Widget::newConnection()
{
    //nextPendingConnection（）取出请求，建立连接套接字，用来通信
    socket = server->nextPendingConnection();
    if(!socket->isValid())
    {
        ui->textEdit->append(server->errorString());
        return;
    }
    tcpClientList.append(socket);
    ui->textEdit->append(QString("client: %1   %2").arg(socket->peerAddress().toString()).arg(socket->peerPort()));

    ui->pushButton_3->setEnabled(true);

    connect(socket,&QTcpSocket::connected,this,[&](){
        ui->textEdit->append("***连接成功***");
    });
    connect(socket,QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error),this,[&](){
        ui->textEdit->append(socket->errorString());
    });
    connect(socket,&QTcpSocket::disconnected,this,[&](){
        for(int i = 0;i<tcpClientList.count();i++)
        {
            if(tcpClientList.at(i)->isValid()){
                ui->textEdit->append(tcpClientList.at(i)->peerAddress().toString()+"已断开连接");
                tcpClientList.removeAt(i);
            }
        }
    });
    connect(socket,&QTcpSocket::readyRead,this,&Widget::recvwork);
}
void Widget::on_pushButton_2_clicked()
{
    server->close();
    ui->label->setStyleSheet("background-color:red;border-radius:50px;");
}

void Widget::on_pushButton_3_clicked()
{
    for(int i=0;i<tcpClientList.count();i++){
        tcpClientList.at(i)->write(ui->textEdit_2->toPlainText().toUtf8());
    }
    ui->textEdit->append("服务器:"+ui->textEdit_2->toPlainText().toUtf8());
    ui->textEdit_2->clear();
}

void Widget::recvwork()
{
    sendRig data;
    for(int i=0;i<tcpClientList.count();i++){
        while (tcpClientList.at(i)->bytesAvailable() >= sizeof(sendRig)) {
//                sendRig msg;
            tcpClientList.at(i)->read(reinterpret_cast<char*>(&data), sizeof(sendRig));


//        if(tcpClientList.at(i)->bytesAvailable()){
//       QByteArray x= tcpClientList.at(i)->readAll();
//        qDebug()<<"---------------"<<x.length()<<x;
//            data = (sendRig*)x.data();

            ui->textEdit->append(QString::number(data.type));
             qDebug()<<"sever------------";
            switch (data.type) {
            case 0:{
                //快递员注册
                sendRig messagr;
                messagr.type =0;
                messagr.IC = courier_register(&data);
                QByteArray arr;
                arr.append((char*)&messagr,sizeof (sendRig));
                tcpClientList.at(i)->write(arr);
                break;
            }
            case 1:{
                //用户注册
                sendRig messagr;
                messagr.type = 1;
                messagr.IC = consignee_register(&data);
                QByteArray arr;
                arr.append((char*)&messagr,sizeof (sendRig));
                tcpClientList.at(i)->write(arr);
                break;
            }
            case 2:{
                //登录
                sendRig messagr;
                messagr.type = 2;
                messagr.IC = user_login(&data,&messagr);
                strcpy(messagr.tele,data.tele);
                ui->textEdit->append(QString::number(messagr.IC));
                ui->textEdit->append("------------");
                ui->textEdit->append(messagr.tele);
                QByteArray arr;
                arr.append((char*)&messagr,sizeof (sendRig));
                tcpClientList.at(i)->write(arr);
                break;
            }
            case 3:{
                //录入订单信息并显示到客户端
                sendRig messagr;
                messagr.type = 3;
                messagr.IC = stg_read(&data);
                QByteArray arr;
                arr.append((char*)&messagr,sizeof (sendRig));
                tcpClientList.at(i)->write(arr);
                break;
            }
            case 4:{
                //用户刷新
                usr_flush(&data,i);
                break;
            }
            case 5:{
                //空柜显示，客户端




                empty_whitch(&data,i);
                break;
            }
            case 6:{
                //空柜显示，开发板
                qDebug()<<"------"<<data.IC<<"----------";
//                if (requestMap.contains(data.IC)) {


//                    QTcpSocket *originalClient = requestMap.take(data.IC); // 取回并移除映射
                    QByteArray arr;
                    arr.append((char*)&data,sizeof (sendRig));
                    qDebug()<<"BBBBBBBBBBBBB:"<<data.IC;
                    tcpClientList.at(data.IC)->write(arr);
                qDebug()<<"CCCCCCCCCCCCCCCCCC";
//                    originalClient->write(arr);
//                            }
                break;
            }
            case 7:{
                //存件
                QByteArray arr;
                // 生成100到999之间的随机整数
                int randomNum = QRandomGenerator::global()->bounded(100, 1000);
                QSqlQuery queryy;
                QString sqll = QString("update order set idenma=%1 where UID-%2")
                        .arg(QString::number(randomNum))
                        .arg(data.ID);
                queryy.prepare(sqll);
                queryy.exec();

                QSqlQuery query_save;
                QString sql_save = QString("select * from order where UID=%1;").arg(data.ID);
                query_save.prepare(sql_save);
                if(!query_save.exec()){
                    qDebug()<<"insert:"<<query_save.lastError().text();
                }
            
                query_save.next();
//                while(query_save.next()){
                    sendRig mess;
                    mess.type=7;
                    strcpy(mess.Account,query_save.value("name").toString().toUtf8());
                    strcpy(mess.ID,query_save.value("UID").toString().toUtf8());
                    strcpy(mess.tele,query_save.value("ctele").toString().toUtf8());
                    strcpy(mess.teletwo,query_save.value("rtele").toString().toUtf8());
                    strcpy(mess.password,query_save.value("idenma").toString().toUtf8());
                    mess.IC = data.IC;
                    arr.append((char*)&mess,sizeof (sendRig));
//                    tcpClientList.at(i)->write(arr);
//                }
                QString add = QString::fromUtf8(data.Account);
                tcpClientList.at(add.toInt())->write(arr);
                break;
            }
            case 8:{
                //存件反馈
                in_return(&data);
                break;
            }
            case 9:{
                //取件反馈
                out_return(&data);
                break;
            }
            }
        }
    }
}
